<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Models\BalanceLog;
use App\Models\CustomerProduct;
use App\Models\CzMobileBlank;
use App\Models\CzOrder;
use App\Models\CzProduct;
use App\Models\CzSpec;
use App\Models\MiniUser;
use App\Models\SysUser;
use App\Services\CzOrderService;
use EasyWeChat\Factory;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;


// 小程序相关接口
class MiniController extends ApiBaseController
{
    protected $baseUrl;
    protected $appid;
    protected $mch_id;
    protected $secret;
    protected $miniApp;
    protected $payApp;
    protected $paykey;


    public function __construct(Request $request)
    {
        $this->baseUrl = env('APP_URL');
        $this->appid = env('min_appid');
        $this->secret = env('min_secret');
        $mch_id = env('mch_id');
        $this->paykey = env('key');
        $notify_url = env('notify_url');
        parent::__construct($request);

        $this->miniApp = Factory::miniProgram([
            'log' => [
                'level' => 'debug',
                'file' => storage_path('wechat.log'),
            ],
            "response_type" => "array",
            "app_id" => $this->appid,
            "secret" => $this->secret,
        ]);

        $config = [
            'app_id' => $this->appid, //appid为小程序appid
            'mch_id' => $mch_id,
            'key' => $this->paykey,
            'cert_path' => base_path(env("cert_path")),
            'key_path' =>  base_path(env("key_path")),
            'notify_url' => $notify_url
        ];
        $this->payApp = Factory::payment($config);
    }
    // 获取首页产品
    public function getHomeProduct(Request $request)
    {
        $data = [
            [
                "face_value" => 50,
                // "sale_price" => 48.5
                "sale_price" => 50.5
            ],
            [
                "face_value" => 100,
                // "sale_price" => 96.99
                "sale_price" => 101
            ],
            [
                "face_value" => 200,
                // "sale_price" => 193.98
                "sale_price" => 202

            ]
        ];
        return success(['data' => $data]);
    }
    public function getQuestion(Request $request)
    {
        $data = [
            [
                "title" => "多久到账?",
                "con" => "
                    <p>一般会在72小时内到账，月初月末缴费高峰期可能会出现延迟到账的情况，还请您谅解!若订单缴费失败，系统会自动退款，请您放心!
                    </p>
                "
            ],
            [
                "title" => "怎样查询是否到账？",
                "con" => "
                    <p>1.用号码拨打运营商客服电话: 移动10086/联通10010/电信10000，转人工服务，要求查询手机号码缴费记录。</p>
                    <p>2.用号码登录运营商手机营业厅，查询订单完成时间的缴费记录。</p>
                    <p>3.通过以上任一种方式查询到缴费记录说明订单缴费成功话费到账。如果查询不到缴费记录，请联系在线客服处理。
                    </p>
                    "
            ],
            [
                "title" => "成功后未收到短信怎么办？",
                "con" => "
                    <p>1.请点击本小程序的“我的订单”页面，先核实你的订单状态是否[充值成功] 及你充值的号码是否无误;</p>
                    <p>2.若以上核实无误后还未收到到账短信通知，可能是欠费停机无法收到短信，运营商偶尔也会有漏发短信的情况，建议你登录手机营业厅或拨打运营商电话，按提示音查询余额及缴费记录;</p>
                    <p>3.若以上问题均排除仍未到账，请将你的充值订单截图及充值号码发送至[在线客服]，客服将进一步为您核实。
                    </p>
                    "
            ],
            [
                "title" => "为什么充值金额不对?",
                "con" => "
                    <p>手机欠费或者是运营商分次充值，如果手机欠费，运营商会将欠费额度抵消之后剩余部分加到账户余额，运营商分批次到账可稍等待，也可以拨打运营商电话查询。
                    </p>
                    "
            ],
            [
                "title" => "充错号码怎么办?",
                "con" => "
                    <p>亲，非常抱歉!您一付款成功，系统就即时发起充值，人工无法拦截，会马上入账，资金也是即时支付给运营商，运营商不支持冲正交易。所以我们和运营商 (移动、联通、电信) 无法给您办理退款，建议尽快联系充错号码机主自行协商。
                    </p>
                    "
            ],
            [
                "title" => "订单充值失败何时退款?",
                "con" => "
                    <p>若充值失败，系统会自动为您办理全额退款。退款方式如下:
                    </p>
                    <p>
                    1.微信钱包支付的，实时退款到微信钱包，可在[微信支付] 服务通知中查询到;
                    </p>
                    <p>
                    2.银行储蓄卡或信用卡支付的，1-5个工作日原路退款到支付的银行卡。退回的银行卡可能不会发送入账通知的短信，请及时留意银行卡进出账单，以便核实退款到账情况。
                    </p>
                    "
            ],
            [
                "title" => "成功后是否可以开具发票?",
                "con" => "
                    <p>本平台暂不提供开票服务，发票一般由运营商提供。你可以到当地营业厅打印发票，或登录网上营业厅下载电子发票，具体政策请咨询对应的运营商。
                    </p>
                    "
            ],
        ];
        return success(['data' => [
            "list" => $data,
            "mobile" => "客服热线: 4001588569",
            "time" => "工作时间：周一至周五9:00-12:00，13:00-18:00(法定节假日休息)",
            "compony" => "",
        ]]);
    }
    public function getLink()
    {
        $res = config('mini')['kxtx'];
        dd($res);
        // $res = $this->miniApp->url_link->generate([
        //     "path" => "pages/record/record",
        //     "query" => ""
        // ]);

        // return success(['data' => $res["url_link"]]);
    }
    public function orderNorifyUrl(Request $request)
    {
        $order_id = request("order_id");
        $pwd = request("pwd");
        $type = request("type");
        if (!$order_id || !$pwd || !$type) {
            return error("fail");
        }
        if ($pwd != "258963") {
            return error("fail");
        }
        $info = CzOrder::find($order_id);
        if (!$info) {
            return error("fail");
        }
        if (!$info->pay_status) {
            return error("fail");
        }
        if ($info->create_by == 25) {
            $miniApp = Factory::miniProgram([
                'log' => [
                    'level' => 'debug',
                    'file' => storage_path('wechat.log'),
                ],
                "response_type" => "array",
                "app_id" => config('mini')['yxyc']['appid'],
                "secret" => config('mini')['yxyc']['secret'],
            ]);
        }
        if ($info->create_by == 26) {
            $miniApp = Factory::miniProgram([
                'log' => [
                    'level' => 'debug',
                    'file' => storage_path('wechat.log'),
                ],
                "response_type" => "array",
                "app_id" => config('mini')['kxtx']['appid'],
                "secret" => config('mini')['kxtx']['secret'],
            ]);
        }
        if ($info->create_by == 27) {
            $miniApp = Factory::miniProgram([
                'log' => [
                    'level' => 'debug',
                    'file' => storage_path('wechat.log'),
                ],
                "response_type" => "array",
                "app_id" => config('mini')['yxwy']['appid'],
                "secret" => config('mini')['yxwy']['secret'],
            ]);
        }


        if ($type == "fail") {
            // 失败通知
            if ($info->create_by == 25) {
                $data = [
                    'template_id' => 'ZJV-yjdQKC7QKD_xfW2LE8o7UtmwbDbVU6jJpRHoJ04', // 所需下发的订阅模板id
                    'touser' => $info->openid,     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'character_string4' => [
                            'value' => $info->order_sn,
                        ],
                        'phone_number1' => [
                            'value' => $info->mobile,
                        ],
                        'amount2' => [
                            'value' => $info->face_value,
                        ],
                        'thing5' => [
                            'value' => "非常抱歉,订单充值失败!",
                        ],
                    ],
                ];
            }
            if ($info->create_by == 26) {
                $data = [
                    'template_id' => 'muHtejppxS9R914WjN2fCfdiyn7NRe5wgLFNOA7vCXA', // 所需下发的订阅模板id
                    'touser' => $info->openid,     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'character_string4' => [
                            'value' => $info->order_sn,
                        ],
                        'phone_number1' => [
                            'value' => $info->mobile,
                        ],
                        'amount2' => [
                            'value' => $info->face_value,
                        ]
                    ],
                ];
            }
            if ($info->create_by == 27) {
                $data = [
                    'template_id' => 'M4vbZCuMzoSNN1Mm1OQewQ1X4sT0sl6Mt6C3HXGDZZ0', // 所需下发的订阅模板id
                    'touser' => $info->openid,     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'character_string3' => [
                            'value' => $info->order_sn,
                        ],
                        'phone_number1' => [
                            'value' => $info->mobile,
                        ],
                        'amount2' => [
                            'value' => $info->face_value,
                        ]
                    ],
                ];
            }
        }
        if ($type == "success") {
            // 成功通知
            if ($info->create_by == 25) {
                $data = [
                    'template_id' => 'Jd0ke1RjhRJtw-on3rGHt4mukRCW3NgmyzxNmvf-pwc', // 所需下发的订阅模板id
                    'touser' => $info->openid,     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'character_string6' => [
                            'value' => $info->order_sn,
                        ],
                        'phone_number5' => [
                            'value' => $info->mobile,
                        ],
                        'amount1' => [
                            'value' => $info->face_value,
                        ],
                        'time3' => [
                            'value' => date('Y-m-d H:i:s', strtotime($info->updated_at)),
                        ],
                        'thing7' => [
                            'value' => "订单已充值成功！",
                        ],
                    ],
                ];
            }
            if ($info->create_by == 26) {
                $data = [
                    'template_id' => 'l0jH7nttsE9tr53PJb8hAyk5FEj2Ub9cSuyBAy1RrfI', // 所需下发的订阅模板id
                    'touser' => $info->openid,     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'character_string4' => [
                            'value' => $info->order_sn,
                        ],
                        'phone_number5' => [
                            'value' => $info->mobile,
                        ],
                        'amount1' => [
                            'value' => $info->face_value,
                        ],
                        'time3' => [
                            'value' => date('Y-m-d H:i:s', strtotime($info->updated_at)),
                        ],
                        'thing7' => [
                            'value' => "订单已充值成功！",
                        ],
                    ],
                ];
            }
            if ($info->create_by == 27) {
                $data = [
                    'template_id' => 'P5jc7JCV68Ob3hzDnIExYYRmdwGUNomaVK67L_Kpdo4', // 所需下发的订阅模板id
                    'touser' => $info->openid,     // 接收者（用户）的 openid
                    'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                    'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                        'character_string4' => [
                            'value' => $info->order_sn,
                        ],
                        'phone_number5' => [
                            'value' => $info->mobile,
                        ],
                        'amount1' => [
                            'value' => $info->face_value,
                        ],
                        'time3' => [
                            'value' => date('Y-m-d H:i:s', strtotime($info->updated_at)),
                        ],
                    ],
                ];
            }
        }

        $res = $miniApp->subscribe_message->send($data);
        logger($info->order_sn . "v1 mini msg send success" . json_encode($res));
        return success($res);
    }
    public function getUserSession(Request $request)
    {
        $code = request('code');
        if (!$code) {
            return error('失败');
        }
        $res = $this->miniApp->auth->session($code);
        // 入库
        $user = MiniUser::updateOrCreate(["openid" => $res['openid']], [
            "session_key" => $res['session_key'],
            "create_by" => 25,
            "update_by" => 25,
            "appid" => $this->appid,
        ]);
        if ($user) {
            logger('user成功:');
        } else {
            logger('user失败:');
        }

        // 返回token
        $token = auth('mini_user')->login($user);
        // logger("token" . $token);
        return success([
            "data" => ['token' => $token, 'expires_in' => auth("mini_user")->factory()->getTTL() * 60]
        ], "登录成功");
    }
    // 获取支付参数
    protected function getPayParams($order, $user)
    {
        // $order = CzOrder::find(4887);
        // dd(date('Y-m-d H:i:s', strtotime($order->updated_at)));
        // $pay_type=  "";
        // if ($user->pay_type == "jinfu") {
        // }
        $channel_file = base_path("payChannel/jinfu/" . "jinfu.php");
        // if (env('third_type') == 1) {
        if ($user->pay_type == "jinfu") {

            $callback_url = env("third_notify_url") . "/jinfu";
            $account = env('third_account');
            $third_key = env('third_key');
        }
        if ($user->pay_type == "jinfu2") {
            $callback_url = env("third_notify_url") . "/jinfu2";
            $account = env('third_account2');
            $third_key = env('third_key2');
        }
        if ($user->pay_type == "tlhsb_yc") {
            logger('miniv1 tlhsb_yc');
            $channel_file = base_path("payChannel/tlhsb/" . "tlhsb.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/tlhsb_yc";
            $setting = config('pay')['tlhsb_yc'];
            $setting['callback_url'] = $callback_url;
            logger("支付参数" . json_encode($setting));

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "tlhsb";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        if ($user->pay_type == "huilian") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian";
            // $account = env('third_account3');
            // $third_key = env('third_key3');
            // logger('pay' . json_encode(config('pay')));
            $setting = config('pay')['huilian'];
            $setting['callback_url'] = $callback_url;

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "huilian";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        if ($user->pay_type == "huilian2") {
            $channel_file = base_path("payChannel/huilian2/" . "huilian2.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian2";
            $setting = config('pay')['huilian2'];
            $setting['callback_url'] = $callback_url;

            $submitData = [
                'OutTradeNo' => $order->order_sn,
                'Body' => $order->product_name ?? '充值支付',
                'TotalAmount' => $order->price * 100,
                'OpenId' => $order->openid,
                'SubAppId' => $this->appid,
                "success_back_page" => ""
            ];
            $payClassName = "huilian2";
            $obj = new $payClassName($setting);

            $res = $obj->submitOrder($submitData);
            $data = [
                "code" => 200,
                "msg" => "",
                "payInfo" => []
            ];
            if ($res['status'] == 1) {
                $data['payInfo'] = $res['payInfo'];
                $data['msg'] = "获取成功";
            } else {
                $data['code'] = 500;
                $data['msg'] = $res['msg'] ?? '支付参数获取失败';
            }
            return $data;
        }
        include_once $channel_file;

        $setting = [
            "account" => $account,
            "key" => $third_key,
            "callback_url" => $callback_url,
        ];
        $payClassName = "jinfu";
        $obj = new $payClassName($setting);
        $order_data = [
            "TotalAmount" => $order->price * 100,
            "OutTradeNo" => $order->order_sn,
            "Body" => $order->product_name,
            "success_back_page" => "",
            "SubAppId" => $this->appid,
            "OpenId" => $order->openid,
        ];
        $res = $obj->submitOrder($order_data);
        $data = [
            "code" => 200,
            "msg" => "",
            "payInfo" => []
        ];

        if ($res['status'] == 1) {
            $data['payInfo'] = $res['payInfo'];
            $data['msg'] = "获取成功";
        } else {
            $data['code'] = 500;
            $data['msg'] = $res['msg'] ?? '支付参数获取失败';
        }
        return $data;
    }
    public function getOrderList(Request $request)
    {
        $params = $request->all();
        $user = auth('mini_user')->user();
        if (!isset($params['mobile'])) {
            // return error('fail');
        }
        $params['openid'] = $user->openid;
        $paginator = CzOrder::filter($params)->where('pay_status', 1)->orderBy("id", 'desc')->select(['id', 'created_at', 'isp', 'order_sn', "product_name", "price", 'face_value', 'mobile', 'area_name', "order_status", "refund_status"])->paginate($this->pageSize);
        $list =  $paginator->items();
        foreach ($list as $key => &$val) {
            $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
            $val['product_name'] = "优惠福利缴费";
            if ($val['isp'] == 1) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/yd_200.jpg";
                }
            }
            if ($val['isp'] == 2) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/lt_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/lt_200.jpg";
                }
            }
            if ($val['isp'] == 3 || $val['isp'] == 4) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/dx_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/dx_200.jpg";
                }
            }
        }
        $result = [
            'rows' => $list,
            'total' => $paginator->total(), // 获取结果集中的数据总数
            'last_page' => $paginator->lastPage(),
            'currentPage' => $paginator->currentPage()
        ];
        return success($result);
    }
    public function getUserInfo(Request $request)
    {
        // $user = auth('mini_user')->user();
        // $info = MiniUser::find($user->id);
        // return  success([
        //     "data" => [
        //         'openid' => $info['openid']
        //     ]
        // ]);
        return success();
    }
    public function getGoodsList(Request $request)
    {
        $data = [
            [
                "img" => "http://ty.hfcz888.net/storage/yd_100.jpg",
                "price" => "96.00",
                "title" => "全国移动慢充100元话费",
                "face_value" => 100,
                "isp" => 1
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/yd_200.jpg",
                "price" => "192.00",
                "title" => "全国移动慢充200元话费",
                "face_value" => 200,
                "isp" => 1
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/lt_100.jpg",
                "price" => "96.00",
                "title" => "全国联通慢充100元话费",
                "face_value" => 100,
                "isp" => 2
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/lt_200.jpg",
                "price" => "192.00",
                "title" => "全国联通慢充200元话费",
                "face_value" => 200,
                "isp" => 2
            ],


            [
                "img" => "http://ty.hfcz888.net/storage/dx_100.jpg",
                "price" => "96.00",
                "title" => "全国电信慢充100元话费",
                "face_value" => 100,
                "isp" => 3
            ],
            [
                "img" => "http://ty.hfcz888.net/storage/dx_200.jpg",
                "price" => "192.00",
                "title" => "全国电信慢充200元话费",
                "face_value" => 200,
                "isp" => 3
            ],
        ];
        return success([
            "data" => $data
        ]);
    }
    public function getMiniBanner(Request $request)
    {

        return success([
            "data" => [
                [
                    "img" => $this->baseUrl . "/storage/youhui.png",
                    "link" => ""
                ],
                [
                    "img" => $this->baseUrl . "/storage/xhzw.png",
                    "link" => ""
                ]
            ]
        ]);
    }
    public function getContact()
    {
        return success([
            "data" => env('APP_URL') . "/storage/contact.jpg"
        ]);
    }
    public function urlCode()
    {
        $str = request('str');
        $type = request('type', 1);
        if ($type == 1) {
            $res = urlencode($str);
        } else {
            $res = urldecode($str);
        }
        return success([
            "data" => ["str" => $res]
        ]);
    }
    public function getLoveInfo()
    {
        $res_str = $this->httpRequest("https://api.uomg.com/api/rand.qinghua");
        $res = json_decode($res_str, true);
        if ($res['code'] == 1) {
            return success(['data' => $res['content']]);
        } else {
            return error('错误');
        }
    }
    public function getAreaByPhone(Request $request)
    {
        $phone =   request('phone');
        if (!is_numeric($phone) || strlen($phone) != 11) {
            return error('手机号码格式有误');
        }
        $mobile_pref = substr($phone, 0, 7);
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            //2todo 通过其它接口查询
            return error('获取归属地失败');
        }
        return success(['data' => $mobile_info]);
    }
    public function getDescImg(Request $request)
    {

        return success([
            "data" => [
                $this->baseUrl . "/storage/tip1.jpg",
                $this->baseUrl . "/storage/tip2.jpg",
            ]
        ]);
    }
    public function getAddressByIp(Request $request)
    {
        $ip = request('ip');
        if (!$ip) {
            // return error('参数错误');
            $ip = request()->ip();
            $res_str = $this->httpRequest("http://opendata.baidu.com/api.php?query=" . $ip . "&co=&resource_id=6006&oe=utf8");
            $res = json_decode($res_str, true);
            if ($res['status'] == 0) {
                return success([
                    "data" => [
                        'ip' => $ip,
                        "address" => $res['data'][0]['location']
                    ]
                ]);
            } else {
                return error(['info' => "查询失败"]);
            }
        } else {
            $res_str = $this->httpRequest("http://opendata.baidu.com/api.php?query=" . $ip . "&co=&resource_id=6006&oe=utf8");
            $res = json_decode($res_str, true);
            if ($res['status'] == 0) {
                return success([
                    "data" => ['info' => $res['data'][0]['location']]
                ]);
            } else {
                return error(['info' => "查询失败"]);
            }
        }
    }
    // 小程序下单
    public function createOrder(Request $request)
    {
        return error('系统紧急维护中，请稍后再试～');
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $type = $params['type'] ?? 1; //1慢充2快充
        // $user_id = $params['user_id'] ?? 25;
        $mini_user = auth('mini_user')->user();
        $user_id = $mini_user->create_by;

        $face_value = intval($params['face_value'] ?? '100'); //面值
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if (strlen($mobile) != 11) {
            return error('手机号码格式有误,必须为11位！');
        }
        if ($this->validateMobileIsBlank($mobile)) {
            return error('号码' . $mobile . '为黑名单号码');
        }
        if (!is_numeric($face_value)) {
            return error('面值不正确');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            logger("归属地获取失败mobile" . $mobile);
            return error("归属地获取失败,请联系客服人员!");
        }
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        if ($province == "安徽" && $isp_name == "电信") {
            return error('安徽电信目前维护中,暂无法充值,抱歉!');
        }
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $mobileCount = CzOrder::where('mobile', $mobile)->where('pay_status', 1)->whereBetween("created_at", [time() - 3600 * 24 * 30, time()])->count();
        if ($mobileCount >= 5) {
            return error('号码下单已上限，请过一段时间再下单，谢谢配合');
        }
        $province_id = $area_info->parent_id;
        // 根据面值和运营商获取客户产品
        //获取用户全部产品
        $user = SysUser::find($user_id);
        // logger("user" . json_encode($user));
        // 客户的所有面值
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        // 比较价格
        // 获取客户产品
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
        if (count($user_product->toArray()) == 0) {
            // logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);
            // todo默认产品下单
            // continue;
            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();

        $cur_user_product_id = $temp_arr[0]['id'];
        foreach ($temp_arr as $key => $val) {
            $product_id = $val['product_id'];
            $prodcut = CzProduct::find($product_id);
            if ($prodcut->city_id) {
                // 分市
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                break;
            } else if ($prodcut->province_id) {
                // 分省
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                break;
            }
        }
        $user_product = CustomerProduct::find($cur_user_product_id);
        // 下单
        $user_price = $user_product->user_price;
        $is_loop = $user_product->is_loop;
        $submit_order_count = $user_product->submit_order_count;
        $user_product_timeout = $user_product->timeout ?? 0;
        $product_info = CzProduct::find($user_product->product_id);
        $spec_info = CzSpec::find($user_product->spec_id);
        $order_sn = 'YXYC' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
        $hf_type = 1;
        if ($type == 1) {
            $hf_type = 2;
        } else {
            $hf_type = 1;
        }
        $order_data = [
            "pay_status" => 0,
            "refund_status" => 0,
            'order_sn' => $order_sn,
            "user_order_sn" => $order_sn,
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $province . '-' . $city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_from' => 'mini',
            'is_auto' => $spec_info->is_auto,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
            "callback_url" => "",
            "create_by" => $user->id,
            "update_by" => $user->id,
            "openid" => $mini_user->openid,
            "appid" => $mini_user->appid
        ];

        //用户分配产品的超时时间
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }
        if (strstr($isp_name, '虚拟') || strstr($isp_name, '物联网')) {
            // 虚拟/物联网-号退
            return error("下单失败,原因:" . $isp_name);
        }
        if (strstr($isp_name, '未知')) {
            // 虚拟号退
            return error("下单失败,原因:" . $isp_name);
        }
        $model = CzOrder::create($order_data);
        $paytime = time();
        // 下单成功获取支付参数
        $result = $this->payApp->order->unify([
            'body' => $product_info->title,
            'out_trade_no' => $order_sn,
            'total_fee' => $user_price * 100,
            'spbill_create_ip' => env('clientIp'), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => env('notify_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            "openid" => $mini_user->openid
            // 'trade_type' => 'MWEB', // 请对应换成你的支付方式对应的值类型
        ]);
        $data = [];
        if ($user->pay_type == "wx") {
            if ($result['return_code'] == "SUCCESS" && $result['result_code'] == 'SUCCESS') {
                $nonce_str = $result['nonce_str'];
                $prepay_id = $result['prepay_id'];
                $paySign   = md5("appId={$this->appid}&nonceStr={$nonce_str}&package=prepay_id={$prepay_id}&signType=MD5&timeStamp={$paytime}&key={$this->paykey}");
                // 返回给小程序
                $res              = [];
                $res['nonceStr']  = $nonce_str;
                $res['timeStamp'] = strval($paytime); // 小程序支付的timeStamp参数，必须使用这个 timeStamp，因为已经计算到了paySign中
                $res['package']   = "prepay_id=" . $prepay_id;
                $res['paySign']   = $paySign;
                $res['signType']  = 'MD5';
                return success(["data" => $res]);
            } else {
                return error($result['err_code_des']);
            }
        } else {
            $payParamsRes = $this->getPayParams($model, $user);
            if ($payParamsRes['code'] == 200) {
                // 第三方支付
                // third_notify_url
                return success(["data" => $payParamsRes['payInfo']]);
            } else {
                logger('下单失败,' . $payParamsRes['msg']);
                return error('下单失败,' . $payParamsRes['msg']);
            }
        }
    }
    public function createOrder2(Request $request)
    {
        return error('系统紧急维护中，请稍后再试～');
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $type = $params['type'] ?? 1; //1慢充2快充
        // $user_id = $params['user_id'] ?? 25;
        $mini_user = auth('mini_user')->user();
        $user_id = $mini_user->create_by;

        $face_value = intval($params['face_value'] ?? '100'); //面值
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if ($this->validateMobileIsBlank($mobile)) {
            return error('号码' . $mobile . '为黑名单号码');
        }
        if (!is_numeric($face_value)) {
            return error('面值不正确');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            logger("归属地获取失败mobile" . $mobile);
            return error("归属地获取失败,请联系客服人员!");
        }
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $province_id = $area_info->parent_id;
        // 根据面值和运营商获取客户产品
        //获取用户全部产品
        $user = SysUser::find($user_id);
        // 客户的所有面值
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        // 比较价格
        // 获取客户产品
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
        if (count($user_product->toArray()) == 0) {
            // logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);
            // todo默认产品下单
            // continue;
            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();

        $cur_user_product_id = $temp_arr[0]['id'];
        foreach ($temp_arr as $key => $val) {
            $product_id = $val['product_id'];
            $prodcut = CzProduct::find($product_id);
            if ($prodcut->city_id) {
                // 分市
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                break;
            } else if ($prodcut->province_id) {
                // 分省
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                break;
            }
        }
        $user_product = CustomerProduct::find($cur_user_product_id);
        // 下单
        $user_price = $user_product->user_price;
        $is_loop = $user_product->is_loop;
        $submit_order_count = $user_product->submit_order_count;
        $user_product_timeout = $user_product->timeout ?? 0;
        $product_info = CzProduct::find($user_product->product_id);
        $spec_info = CzSpec::find($user_product->spec_id);
        $order_sn = 'CZ' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
        $hf_type = 1;
        if ($type == 1) {
            $hf_type = 2;
        } else {
            $hf_type = 1;
        }
        $order_data = [
            "pay_status" => 0,
            "refund_status" => 0,
            'order_sn' => $order_sn,
            "user_order_sn" => $order_sn,
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $province . '-' . $city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_from' => 'mini',
            'is_auto' => $spec_info->is_auto,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
            "callback_url" => "",
            "create_by" => $user->id,
            "update_by" => $user->id,
            "openid" => $mini_user->openid,
            "appid" => $mini_user->appid,
        ];

        //用户分配产品的超时时间
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }
        if (strstr($isp_name, '虚拟') || strstr($isp_name, '物联网')) {
            // 虚拟/物联网-号退
            return error("下单失败,原因:", $isp_name);
        }
        if (strstr($isp_name, '未知')) {
            // 虚拟号退
            return error("下单失败,原因:", $isp_name);
        }
        $model = CzOrder::create($order_data);
        // 判断支付
        $user->pay_type = "huilian";
        if ($user->pay_type == "wx") {
            $paytime = time();
            // 下单成功获取支付参数
            $result = $this->payApp->order->unify([
                'body' => $product_info->title,
                'out_trade_no' => $order_sn,
                'total_fee' => $user_price * 100,
                'spbill_create_ip' => env('clientIp'), // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => env('notify_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                "openid" => $mini_user->openid
                // 'trade_type' => 'MWEB', // 请对应换成你的支付方式对应的值类型
            ]);
            $data = [];
            if ($result['return_code'] == "SUCCESS" && $result['result_code'] == 'SUCCESS') {
                $nonce_str = $result['nonce_str'];
                $prepay_id = $result['prepay_id'];
                $paySign   = md5("appId={$this->appid}&nonceStr={$nonce_str}&package=prepay_id={$prepay_id}&signType=MD5&timeStamp={$paytime}&key={$this->paykey}");
                // 返回给小程序
                $res              = [];
                $res['nonceStr']  = $nonce_str;
                $res['timeStamp'] = strval($paytime); // 小程序支付的timeStamp参数，必须使用这个 timeStamp，因为已经计算到了paySign中
                $res['package']   = "prepay_id=" . $prepay_id;
                $res['paySign']   = $paySign;
                $res['signType']  = 'MD5';
                return success(["data" => $res]);
            } else {
                return error($result['err_code_des']);
            }
        } else {
            logger('三方支付');
            $payParamsRes = $this->getPayParams($model, $user);
            if ($payParamsRes['code'] == 200) {
                // 第三方支付
                // third_notify_url
                return success(["data" => $payParamsRes['payInfo']]);
            } else {
                return error('下单失败,' . $payParamsRes['msg']);
            }
        }
    }
    // 获取产品说明图
    public function getMiniDetailImg(Request $request)
    {
        $isp = request("isp");
        $face_value = request("face_value");
        if (!$isp || !$face_value) {
            return error('失败');
        }
        $img = "http://ty.hfcz888.net/storage/yd_100.jpg";

        if ($isp == 1) {
            if ($face_value == 100) {
                $img = "http://ty.hfcz888.net/storage/yd_100.jpg";
            }
            if ($face_value == 200) {
                $img = "http://ty.hfcz888.net/storage/yd_200.jpg";
            }
        }
        if ($isp == 2) {
            if ($face_value == 100) {
                $img = "http://ty.hfcz888.net/storage/lt_100.jpg";
            }
            if ($face_value == 200) {
                $img = "http://ty.hfcz888.net/storage/lt_200.jpg";
            }
        }
        if ($isp == 3 || $isp == 4) {
            if ($face_value == 100) {
                $img = "http://ty.hfcz888.net/storage/dx_100.jpg";
            }
            if ($face_value == 200) {
                $img = "http://ty.hfcz888.net/storage/dx_200.jpg";
            }
        }
        return success(['data' => $img]);

        // return success([
        //     "data" => $this->baseUrl . "/storage/banner1.jpg",
        // ]);
    }
    public function getOrderInfo()
    {
        $mobile = request("mobile");
        if (!$mobile || strlen($mobile) != 11) {
            return error('请输入正确的手机号!');
        }
        $start_time = time() - 30 * 24 * 60 * 60;
        $end_time = time();
        $list = CzOrder::where('pay_status', 1)->where('mobile', $mobile)->whereBetween('created_at', [$start_time, $end_time])->orderBy('id', 'desc')->get(['id', 'order_sn', 'order_status', 'price', 'isp', 'product_name', 'mobile', 'area_name', 'face_value', 'created_at'])->toArray();

        foreach ($list as $key => &$val) {
            $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
            if ($val['isp'] == 1) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/yd_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/yd_200.jpg";
                }
            }
            if ($val['isp'] == 2) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/lt_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/lt_200.jpg";
                }
            }
            if ($val['isp'] == 3) {
                if ($val['face_value'] == 100) {
                    $val['img'] = "http://ty.hfcz888.net/storage/dx_100.jpg";
                }
                if ($val['face_value'] == 200) {
                    $val['img'] = "http://ty.hfcz888.net/storage/dx_200.jpg";
                }
            }
        }

        return success(['data' => $list]);
    }
    public function validateMobileIsBlank($mobile)
    {
        return  CzMobileBlank::where('mobile', $mobile)->exists();
    }
    public function httpRequest($url, $method = 'GET', $postfields = null, $cookie = '', $refer = '', $headers = array(), $debug = false)
    {
        //header("Content-type:text/html;charset=utf-8");
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_COOKIE, $cookie);/* * *COOKIE带过去** */
        //伪造来源referer
        //        curl_setopt ($ci,CURLOPT_REFERER,'http://sb777.cn:8080/tohersystem/rechargeOrder.do?action=distribution&isDistribution=true');
        curl_setopt($ci, CURLOPT_REFERER, $refer);

        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
}
